package com.demo.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;


public abstract class WebRequestUtils {
    public static Map<String, String> getParametersMap(HttpServletRequest request) {
        @SuppressWarnings("unchecked")
        Enumeration<String> paramNames = request.getParameterNames();
        Map<String, String> params = new TreeMap<String, String>();
        while (paramNames != null && paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            String[] values = request.getParameterValues(paramName);
            params.put(paramName, processValue(paramName, values));
        }
        return params;
    }
    public static String processValue(String name, String[] values) {
        String[] sensitiveNames = { "answer", "password", "creditcard" };
        for (String it : sensitiveNames) {
            if (name.toLowerCase().contains(it)) {
                return StringUtils.repeat("*", it.length());
            }
        }
        return Arrays.toString(values);
    }
	public static void setContentDispositionHeader(HttpServletRequest request, HttpServletResponse response, String filename)
			throws UnsupportedEncodingException {
		if (request != null && isBelowInternetExplorer8(request)) {
            String encoded = URLEncoder.encode(filename, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + encoded + "\"");
        } else {
            response.setHeader("Content-Disposition",
                    MimeHelper.encodeContentDisposition("attachment", filename));
        }
	}
    private static boolean isBelowInternetExplorer8(HttpServletRequest request) {
        String userAgentHeader = request.getHeader("User-Agent");
        if (userAgentHeader == null) {
            return false;
        }
        int ieStartIndex = userAgentHeader.toLowerCase().indexOf("msie");
        if (ieStartIndex == -1) {
            return false;
        }
        int ieEndIndex = userAgentHeader.indexOf(";", ieStartIndex + "msie".length());
        if (ieEndIndex == -1) {
            return false;
        }
        String versionString = userAgentHeader.substring(ieStartIndex + "msie".length(), ieEndIndex).trim();
        try {
            Float version = Float.parseFloat(versionString);
            return version < 9;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
